$(function () {

  var cartList = utils.getLocalDataArray('cartList');
  var count = 0;
  cartList.forEach(function (e, i) {
    count += e.number;
  });
  $('.shopcar>.count').text(count);


  function calculateNumberAndTotal() {
    var count = 0;
    var totalMoney = 0;
    //计算
    var temp = [];
    var selected = $(".item-ck:checked");
    cartList.forEach(function (e, i) {
      selected.each(function (index, item) {
        var pID = $(this).parents('.item').attr('pID');
        if (pID == e.pID) {
          temp.push(e);
        }
      });
    });
    temp.forEach(function (e) {
      count += e.number;
      totalMoney += e.price * e.number;
    });
    $('.selected').text(count);
    $('.total-money').text(totalMoney);
  }

  //加载列表
  var cartList = utils.getLocalDataArray('cartList');
  // console.log(cartList);
  if (cartList.length !== 0) {
    $('.empty-tip').addClass('hidden');
    $('.total-of').removeClass('hidden');
    cartList.forEach(e => {
      var singleTotal = e.number * e.price;
      var html = `<div class="item" pID="${e.pID}" >
            <div class="row">
              <div class="cell col-1 row">
                <div class="cell col-1">
                  <input type="checkbox" class="item-ck" checked>
                </div>
                <div class="cell col-4">
                  <img src="${e.imgSrc}" alt="">
                </div>
              </div>
              <div class="cell col-4 row">
                <div class="item-name">${e.name}</div>
              </div>
              <div class="cell col-1 tc lh70">
                <span>￥</span>
                <em class="price">${e.price}</em>
              </div>
              <div class="cell col-1 tc lh70">
                <div class="item-count">
                  <a href="javascript:void(0);" class="reduce fl">-</a>
                  <input autocomplete="off" type="text" class="number fl" value="${e.number}">
                  <a href="javascript:void(0);" class="add fl">+</a>
                </div>
              </div>
              <div class="cell col-1 tc lh70">
                <span>￥</span>
                <em class="computed">${singleTotal}</em>
              </div>
              <div class="cell col-1">
                <a href="javascript:void(0);" item-id="${e.pID}" class="item-del">从购物车中移除</a>
              </div>
            </div>
          </div>`;

      $('.item-list').append(html).removeClass('hidden');
      $('.cart-header').removeClass('hidden');

    });
    calculateNumberAndTotal();
  }
  // 全选
  $('.pick-all').on('click', function () {
    var status = $(this).prop('checked');
    $('.item-ck').prop('checked', status);
    $('.pick-all').prop('checked', status);
    if (!status) {
      $('.selected').text(0);
      $('.total-money').text(0);
    } else {
      calculateNumberAndTotal();
    }
  });

  // 单选
  $('.item-list').on('click', '.item-ck', function () {
    var selected = $(".item-ck:checked");
    var list = $('.item-ck');
    var pickAll = selected.length === list.length;
    $('.pick-all').prop('checked', pickAll);

    //计算
    calculateNumberAndTotal();
  });

  $('.item-list').on('click', '.add', function () {
    var pID = $(this).parents('.item').attr('pID');
    var text = $(this).prev();
    var number = parseInt(text.val());
    number++;
    text.val(number);

    var currentGood = cartList.find(function (e, i) {
      return e.pID == pID;
    })

    currentGood.number = number;

    utils.saveLocalDataArray('cartList', cartList);

    var total = currentGood.number * currentGood.price;
    $(this).parents('.item').find('.computed').text(total);

    calculateNumberAndTotal();
  });
  $('.item-list').on('click', '.reduce', function () {
    var $this = $(this);
    if ($this.hasClass('disabled')) {
      return;
    }
    var pID = $this.parents('.item').attr('pID');

    var text = $this.next();
    var number = parseInt(text.val());
    number--;
    number = number <= 1 ? 1 : number;
    if (number === 1) {
      $this.addClass('disabled');
    }

    text.val(number);
    var currentGood = cartList.find(function (e, i) {
      return e.pID == pID;
    })

    currentGood.number = number;

    utils.saveLocalDataArray('cartList', cartList);

    var total = currentGood.number * currentGood.price;
    $this.parents('.item').find('.computed').text(total);

    calculateNumberAndTotal();
  });

  $('.item-list').on('click', '.item-del', function () {
    var pID = $(this).attr('item-id');
    var _this = this;

    $('.mask').removeClass('hidden');
    $("#dialog-confirm").dialog({
      resizable: false,
      height: 180,
      modal: true,
      buttons: {
        "确认删除": function () {
          if (utils.deleteLocalDataById('cartList', pID)) {
            $(_this).parents('.item').remove();
          }

          dialogClose();
          calculateNumberAndTotal();
        },
        "取消": function () {
          dialogClose();
        }
      }
    });
  });

  function dialogClose() {
    $("#dialog-confirm").dialog("close");
    $('.mask').addClass('hidden');
  }

  $('.item-list').on('change keydown', '.number', function (e) {
    if (e.type === 'change' || e.keyCode === 13) {
      var pID = $(this).parents('.item').attr('pID');
      var number = parseInt($(this).val());

      var currentGood = cartList.find(function (e, i) {
        return e.pID == pID;
      })

      currentGood.number = number;

      utils.saveLocalDataArray('cartList', cartList);

      calculateNumberAndTotal();
    }

  })

});